<?php


namespace BeReborn\Service\Common;


use BeReborn\Core\JSON;
use BeReborn\Error\Logger;
use BeReborn\Http\Context;
use Swoole\Server;

/**
 * Class ServerPacket
 * @package BeReborn\Service\Common
 */
class ServerPacket extends Port
{

	/**
	 * @param Server $server
	 * @param $data
	 * @param $clientInfo
	 * @return mixed
	 * @throws
	 */
	public function onPacket($server, $data, $clientInfo)
	{
		try {
			if (!is_array($data = unserialize($data))) {
				throw new \Exception('Data parsing failed.', 601);
			}

			if (!isset($data['body'])) $data['body'] = [];

			$this->newRequestInstance($data, 0, $clientInfo);

			$routerData = router()->runHandler();
			if (!is_string($routerData)) {
				$routerData = JSON::encode($routerData);
			}
			return $server->sendto($clientInfo['address'], $clientInfo['port'], $routerData);
		} catch (\Throwable $exception) {
			$json = JSON::to($exception->getCode(), $exception->getMessage());
			return $server->sendto($clientInfo['address'], $clientInfo['port'], $json);
		} finally {
			fire(ServerRequest::AFTER_REQUEST);
			Logger::insert();
		}
	}

}
